package com.oniontech.stamptour.module.nfc;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Parcelable;
import android.util.Log;

import com.oniontech.stamptour.MainActivity;

import java.util.Arrays;

/**
 * Created by kty on 14. 1. 24.
 */
@SuppressLint("NewApi")
public class StampNfcManager {
    private NfcAdapter nfcAdapter = null;
    private Activity context = null;
    private PendingIntent mPendingIntent = null;
    private IntentFilter[] mIntentFilters;
    private String[][] mNFCTechLists;
    private NfcCompleteListener listener = null;

    public StampNfcManager(Activity context) {
        this.context = context;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            this.nfcAdapter = NfcAdapter.getDefaultAdapter(context);
            if (isUsingNfc()) {
                enableWriteMode();
            }
        }
    }

    private boolean isUsingNfc() {
        boolean result = false;

        if (this.nfcAdapter == null) {
            result = false;
        } else {
            result = true;
        }

        return result;
    }

    public void onNewIntent(Intent intent, NfcCompleteListener listener) {
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            Parcelable[] data = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            String payloadData = null;
            String contKey = null;

            if (data != null) {
                try {
                    for (int i = 0; i < data.length; i++) {
                        NdefRecord[] recs = ((NdefMessage) data[i]).getRecords();
                        for (int j = 0; j < recs.length; j++) {

                            byte[] payload = recs[j].getPayload();
                            String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";
                            int langCodeLen = payload[0] & 0077;
                            payloadData = new String(payload);
                            Log.d("nfc", "###################### textEncoding : " + textEncoding);
                            Log.d("nfc", "###################### payload : " + payloadData);
                            Log.d("nfc", "###################### langCodeLen : " + langCodeLen);

                        }
                    }
                } catch (Exception e) {
                    Log.e("TagDispatch", e.toString());
                }

                contKey = "http://"+payloadData.substring(payloadData.indexOf("m.cha.go.kr/korea/heritage"), payloadData.indexOf(",11")+",11".length());
                Log.d("nfc", "###################### langCodeLen : " + contKey);
                listener.getPayload(payloadData);
                listener.getContKey(contKey);
            }
        }
    }

    private void enableWriteMode() {
        Intent mIntent = new Intent(context, MainActivity.class);
        mPendingIntent = PendingIntent.getActivity(context, 0, mIntent, 0);
//        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
//        try {
//            ndef.addDataType("*/*");
//        } catch (IntentFilter.MalformedMimeTypeException e) {
//            throw new RuntimeException("fail", e);
//        }
//
//        mIntentFilters = new IntentFilter[]{
//                ndef,
//        };
//
//        mNFCTechLists = new String[][]{
//                new String[]{
//                        NfcA.class.getName(),
//                        // NfcB.class.getName(),
//                        // NfcF.class.getName(),
//                }
//        };
//
//        context.registerReceiver(nfcTagListener, ndef);

    }

//    BroadcastReceiver nfcTagListener = new BroadcastReceiver() {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//
//            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
//                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
//                Log.d("nfc", "" + tag.getId());
//            }
//        }
//    };

    public void onResume() {
        if (nfcAdapter != null)
            nfcAdapter.enableForegroundDispatch(context, mPendingIntent, mIntentFilters, mNFCTechLists);
    }

    public void onPause() {
        if (nfcAdapter != null)
            nfcAdapter.disableForegroundDispatch(context);
    }

    public interface NfcCompleteListener {
        public void getPayload(String payload);

        public void getContKey(String key);
    }
}
